const db = require('../db/connMysql');
const mysql_tool = require('../util/mysql_tool');
const minio = require('../db/connMinio');

const fileDao = {
    // 创建上传节点
    async createFileNode() {
        let sql = `insert into PublicImg (browser, uri) values (?, ?)`;
        let data = ['public', ''];
        return mysql_tool.execSql(sql, data);
    },
    // 获取预签名URL
    async getUploadUrl(imgId) {
        let res = await minio.getUploadUrl('public', String(imgId), 36000);
        if (res.success) {
            let sql = `UPDATE PublicImg SET uri = ?, status = ? WHERE id = ?`;
            let data = [ imgId, '上传中', imgId ];
            await mysql_tool.execSql(sql, data);
        }
        return res;
    },
    // 标记图片上传完成
    async markUploadComplete(imgId) {
        let sql = `UPDATE PublicImg SET status = ? WHERE id = ?`;
        let data = [ '已完成', imgId ];
        return mysql_tool.execSql(sql, data);
    },
    // 下载文件
    async downloadPublicFile(fileId) {
        let sql = `select browser, uri from PublicImg where id = ? and status = ?`;
        let data = [ fileId, '已完成' ];
        let result = await mysql_tool.execSql(sql, data);
        if (result.length === 0) {
            return { success: false, message: '文件不存在' };
        }
        let { browser, uri } = result[0];
        return minio.getDownloadUrl(browser, uri, 36000);
    }
};

module.exports = fileDao;